package com.rdgzs.framework.servlet;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rdgzs.framework.constant.SysConstants;
import com.rdgzs.framework.utilsTools.CaptchaBuilder;

/**
* ###################################################
* 创建日期：2012-12-27 22:58:45
* 开发人员：李广彬
* 功能描述：生成验证码图片和相应的随机数 回写到前台
* 修改日志： 
* ###################################################
*/
public class CaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		HttpSession session = req.getSession();
		String sessionKey = SysConstants.CAPTCHA;
		try {
			String key = (String) req.getAttribute("key");
			if (key != null && key.trim().length() > 0) {
				sessionKey = key;
			}
			res.setContentType("image/jpeg");
			res.setHeader("Pragma", "No-cache");
			res.setHeader("Cache-Control", "no-cache");
			res.setDateHeader("Expires", 0);
			CaptchaBuilder picRand = CaptchaBuilder.getInstance().createRandCode();
			ImageIO.write(picRand.getImage(), "JPEG", res.getOutputStream());
			session.removeAttribute(sessionKey);
			session.setAttribute(sessionKey, picRand.getRandStr());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}